import React, { useEffect, useState } from "react";
import { createBrowserRouter, createHashRouter, type RouteObject } from "react-router";
import { RouterProvider } from "react-router/dom";
import { useMenuStore } from "@/store/menus";
import { useShallow } from "zustand/react/shallow";
import { getCookieToken } from "@/utils/cookies";
import { generateRouter } from "./helper/GenerateRouter";
import { usePermissions } from "@/hooks/modules/usePermissions";
import { staticRenderRoutes } from "./helper/StaticRenderRouter";
import RegisterThemeHooks from "@/hooks/modules/useTheme";
import RegisterHooks from "@/hooks";

const Router: React.FC = () => {
  const { authMenuList } = useMenuStore(useShallow((state) => ({ authMenuList: state.authMenuList })));
  const [renderRoutes, setRenderRoutes] = useState<RouteObject[]>(staticRenderRoutes);

  const { initPermissions } = usePermissions();

  // 注册全局 Toast 和 theme Hooks
  RegisterHooks();
  RegisterThemeHooks();

  useEffect(() => {
    if (!authMenuList.length) {
      initPermissions(getCookieToken() as string).then(() => {});
      return;
    }
    setRenderRoutes(generateRouter(authMenuList) as RouteObject[]);
  }, [authMenuList]);

  return <RouterProvider router={import.meta.env.VITE_APP_ROUTER_MODE === "hash" ? createHashRouter(renderRoutes) : createBrowserRouter(renderRoutes)} />;
};

export default Router;
